import logging
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text

from app.core.config import settings
from app.db.session import engine, Base
from app.api.v1 import api_router
from app.xxl_job.executor import init_executor
from app.services.storage_service import storage_service

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    logger.info("Starting application...")
    
    # 创建数据库表
    try:
        Base.metadata.create_all(bind=engine)
        logger.info("Database tables created successfully")
    except Exception as e:
        logger.error(f"Failed to create database tables: {e}")
    
    # 测试数据库连接
    try:
        with engine.connect() as conn:
            result = conn.execute(text("SELECT 1"))
            logger.info("Database connection successful")
    except Exception as e:
        logger.error(f"Database connection failed: {e}")
    
    # 初始化XXL-Job执行器
    try:
        xxl_executor = init_executor(app)
        logger.info(f"XXL-Job executor initialized on port {settings.XXL_JOB_EXECUTOR_PORT}")
    except Exception as e:
        logger.error(f"Failed to initialize XXL-Job executor: {e}")
    
    # 测试各个服务
    try:
        from app.services.ai_service import ai_service
        from app.services.storage_service import storage_service
        from app.services.playwright_service import playwright_service
        from app.services.xiaohongshu_service import xiaohongshu_service
        
        logger.info(f"AI Service available: {ai_service.is_available()}")
        logger.info(f"Storage Service available: {storage_service.is_available()}")
        
        # 初始化小红书服务的Firefox浏览器实例
        try:
            browser_init_success = await xiaohongshu_service.initialize()
            if browser_init_success:
                logger.info("小红书服务Firefox浏览器初始化成功，已启用持久化登录状态")
            else:
                logger.warning("小红书服务Firefox浏览器初始化失败")
        except Exception as browser_error:
            logger.error(f"小红书服务浏览器初始化失败: {browser_error}")
        
        # 测试浏览器环境（可选）
        if settings.DEBUG:
            browser_test = await playwright_service.test_browser()
            logger.info(f"Browser test: {browser_test.get('message', 'Unknown')}")
    
    except Exception as e:
        logger.error(f"Service initialization check failed: {e}")
    
    logger.info("Application startup completed")
    
    yield
    
    # 关闭时执行
    logger.info("Shutting down application...")
    
    # 关闭小红书服务浏览器（保持持久化状态）
    try:
        from app.services.xiaohongshu_service import xiaohongshu_service
        await xiaohongshu_service.close()
        logger.info("小红书服务浏览器已安全关闭")
    except Exception as e:
        logger.error(f"关闭小红书服务浏览器失败: {e}")
    
    # 停止XXL-Job执行器自动注册
    try:
        from app.xxl_job.executor import xxl_job_executor
        if xxl_job_executor:
            xxl_job_executor.stop_registry()
            logger.info("XXL-Job executor auto registry stopped")
    except Exception as e:
        logger.error(f"Failed to stop XXL-Job executor registry: {e}")


# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.VERSION,
    description="小红书AI运营工具后端服务",
    lifespan=lifespan
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 创建静态文件目录
static_dir = os.path.join(os.getcwd(), "static")
os.makedirs(static_dir, exist_ok=True)
os.makedirs(os.path.join(static_dir, "qr_codes"), exist_ok=True)

# 挂载静态文件
app.mount("/static", StaticFiles(directory=static_dir), name="static")

# 注册API路由
app.include_router(api_router, prefix="/api/v1")


@app.get("/")
def read_root():
    """根路径"""
    return {
        "message": "小红书AI运营工具后端服务",
        "version": settings.VERSION,
        "status": "running"
    }


@app.get("/health")
def health_check():
    """健康检查"""
    # 检查数据库连接
    db_status = "connected"
    try:
        with engine.connect() as conn:
            conn.execute(text("SELECT 1"))
    except Exception:
        db_status = "disconnected"
    
    # 检查存储服务
    storage_status = "available"
    try:
        if hasattr(storage_service, 'is_available'):
            storage_status = "available" if storage_service.is_available() else "unavailable"
    except Exception:
        storage_status = "unavailable"
    
    return {
        "status": "healthy",
        "version": settings.VERSION,
        "services": {
            "database": db_status,
            "storage_service": storage_status
        }
    }


@app.get("/info")
def app_info():
    """应用信息"""
    return {
        "app_name": settings.APP_NAME,
        "version": settings.VERSION,
        "debug": settings.DEBUG,
        "xxl_job_executor": {
            "app_name": settings.XXL_JOB_EXECUTOR_APP_NAME,
            "port": settings.XXL_JOB_EXECUTOR_PORT
        },
        "storage": {
            "provider": settings.STORAGE_PROVIDER,
            "bucket": settings.S3_BUCKET
        },
        "ai": {
            "provider": settings.LLM_PROVIDER
        }
    }


if __name__ == "__main__":
    import uvicorn
    
    uvicorn.run(
        "app.main:app",
        host="0.0.0.0",
        port=8000,
        reload=settings.DEBUG,
        log_level="info"
    )